﻿using Markdig;

namespace KnownCMS;

class CacheInfo
{
    public DateTime Time { get; set; }
    public string Html { get; set; }
}

/// <summary>
/// 内容系统效用类。
/// </summary>
public class CmsUtils
{
    internal static Dictionary<string, CacheInfo> CachedPosts = [];

    /// <summary>
    /// 将Markdown文本转换成HTML文本，有缓存取缓存。
    /// </summary>
    /// <param name="info">内容明细信息。</param>
    /// <returns>HTML文本。</returns>
    public static MarkupString GetMarkdownHtml(PostDetailInfo info)
    {
        if (info == null)
            return new MarkupString("");

        var html = string.Empty;
        if (CachedPosts.ContainsKey(info.Id))
        {
            var item = CachedPosts[info.Id];
            if (item.Time < info.PublishTime.Value)
            {
                item.Html = GetHtml(info.Content);
                CachedPosts[info.Id] = item;
            }
            html = item.Html;
        }
        else
        {
            html = GetHtml(info.Content);
            CachedPosts[info.Id] = new CacheInfo { Time = info.PublishTime.Value, Html = html };
        }
        return new MarkupString(html);
    }

    /// <summary>
    /// 将Markdown文本转换成HTML文本，有缓存取缓存。
    /// </summary>
    /// <param name="info">回复明细信息。</param>
    /// <returns>HTML文本。</returns>
    public static MarkupString GetMarkdownHtml(ReplyListInfo info)
    {
        if (info == null)
            return new MarkupString("");

        var html = string.Empty;
        if (CachedPosts.ContainsKey(info.Id))
        {
            var item = CachedPosts[info.Id];
            if (item.Time < info.ReplyTime)
            {
                item.Html = GetHtml(info.Content);
                CachedPosts[info.Id] = item;
            }
            html = item.Html;
        }
        else
        {
            html = GetHtml(info.Content);
            CachedPosts[info.Id] = new CacheInfo { Time = info.ReplyTime, Html = html };
        }
        return new MarkupString(html);
    }

    /// <summary>
    /// 将Markdown文本转换成HTML文本。
    /// </summary>
    /// <param name="markdown">Markdown文本。</param>
    /// <returns>HTML文本。</returns>
    public static MarkupString GetMarkdownHtml(string markdown)
    {
        if (string.IsNullOrWhiteSpace(markdown))
            return new MarkupString("");

        var html = GetHtml(markdown);
        return new MarkupString(html);
    }

    private static string GetHtml(string markdown)
    {
        var pipelineBuilder = new MarkdownPipelineBuilder()
            .UsePipeTables()
            .UseBootstrap();
        pipelineBuilder.UseAdvancedExtensions();
        var pipeline = pipelineBuilder.Build();
        return Markdown.ToHtml(markdown, pipeline);
    }
}